package cn.xwt.weidisk.handler;

import cn.xwt.weidisk.pojo.dao.UserDo;
import cn.xwt.weidisk.pojo.dto.Resp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 薛慰涛
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取用户信息
        UserDo userDo = (UserDo)authentication.getPrincipal();
        // 设置返回信息
        Map<String, String> loginSuccessInfo = new HashMap<>(1);
        loginSuccessInfo.put("username", userDo.getUsername());
        loginSuccessInfo.put("role", userDo.getRole());
        // 设置响应信息
        Resp loginMsg = new Resp("00000", "登录成功", loginSuccessInfo);
        response.setContentType("application/json;charset=utf-8");
        // 输出响应信息
        Writer out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(loginMsg));
        out.flush();
        out.close();
    }
}
